<template>
  <div>
    <el-form
      ref="formRef"
      :model="formModel"
      label-position="top"
      class="person-form"
    >
      <el-form-item label="人员信息" prop="person">
        <div class="card-list-container">
          <el-card
            v-for="(personItem, index) in formModel.person"
            :key="index"
            shadow="never"
            class="person-card"
          >
            <el-row :gutter="20" align="middle">
              <el-col :span="20">
                <el-row :gutter="24">
                  <el-col :span="8">
                    <el-form-item
                      label="姓名 (Name)"
                      :prop="'person.' + index + '.name'"
                      :rules="rules.name"
                    >
                      <el-input
                        v-model="personItem.name"
                        placeholder="请输入姓名"
                      />
                    </el-form-item>
                  </el-col>

                  <el-col :span="8">
                    <el-form-item
                      label="IP 地址 (IPv4)"
                      :prop="'person.' + index + '.ip'"
                      :rules="rules.ip"
                    >
                      <el-input
                        v-model="personItem.ip"
                        placeholder="例如: 192.168.1.1"
                      />
                    </el-form-item>
                  </el-col>

                  <el-col :span="8">
                    <el-form-item
                      label="MAC 地址"
                      :prop="'person.' + index + '.mac'"
                      :rules="rules.mac"
                    >
                      <el-input
                        v-model="personItem.mac"
                        placeholder="例如: 00:1A:2B:3C:4D:5E"
                      />
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-col>

              <el-col :span="4" class="action-buttons">
                <el-button
                  v-if="index > 0"
                  type="danger"
                  :icon="Delete"
                  circle
                  @click="removePersonItem(index)"
                />
                <el-button
                  v-if="index === formModel.person.length - 1"
                  type="primary"
                  :icon="Plus"
                  circle
                  @click="addPersonItem"
                />
              </el-col>
            </el-row>
          </el-card>
        </div>
      </el-form-item>

      <el-form-item class="form-footer">
        <el-button type="primary" @click="submitForm(formRef)">提交</el-button>
        <el-button @click="resetForm(formRef)">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref } from "vue";
import { ElMessage, type FormInstance, type FormRules } from "element-plus";
import { Plus, Delete } from "@element-plus/icons-vue";

// 定义 Person 项的 TypeScript 接口
interface PersonItem {
  name: string;
  ip: string;
  mac: string;
}

// Element Plus 表单实例的引用
const formRef = ref<FormInstance>();

// 表单的响应式数据模型
const formModel = reactive<{ person: PersonItem[] }>({
  person: [
    {
      name: "",
      ip: "",
      mac: "",
    },
  ],
});

// --- 自定义校验规则 ---

// IPv4 地址校验器
const validateIp = (rule: any, value: any, callback: any) => {
  if (!value) {
    // 'required: true' 会处理空值情况，但为保险起见保留
    return callback(new Error("IP 地址不能为空"));
  }
  // 正则表达式用于校验 IPv4 地址
  const ipv4Regex =
    /^(?:(?:25[-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
  if (!ipv4Regex.test(value)) {
    callback(new Error("请输入有效的 IPv4 地址"));
  } else {
    callback();
  }
};

// MAC 地址校验器
const validateMac = (rule: any, value: any, callback: any) => {
  if (!value) {
    return callback(new Error("MAC 地址不能为空"));
  }
  // 正则表达式用于校验 MAC 地址 (支持 : 和 - 作为分隔符)
  const macRegex = /^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$/;
  if (!macRegex.test(value)) {
    callback(new Error("请输入有效的 MAC 地址，例如: 00:1A:2B:3C:4D:5E"));
  } else {
    callback();
  }
};

// 将校验规则绑定到表单
const rules = reactive<FormRules>({
  name: [{ required: true, message: "姓名不能为空", trigger: "blur" }],
  ip: [{ required: true, validator: validateIp, trigger: "blur" }],
  mac: [{ required: true, validator: validateMac, trigger: "blur" }],
});

// --- 表单操作方法 ---

// 新增一个 Person 项
const addPersonItem = () => {
  formModel.person.push({
    name: "",
    ip: "",
    mac: "",
  });
};

// 根据索引删除一个 Person 项
const removePersonItem = (index: number) => {
  formModel.person.splice(index, 1);
};

// 提交表单
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log("校验成功，提交的数据:", formModel.person);
      ElMessage({
        message: "提交成功!",
        type: "success",
      });
    } else {
      console.log("校验失败:", fields);
      ElMessage({
        message: "表单校验失败，请检查输入项。",
        type: "error",
      });
    }
  });
};

// 重置表单
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  // 将表单数据重置为初始状态（一个空项）
  formModel.person = [{ name: "", ip: "", mac: "" }];
  // 清除表单的校验状态
  formEl.resetFields();
};
</script>

<style scoped>
/* 卡片列表的容器，确保宽度100% */
.card-list-container {
  width: 100%;
}

.person-card {
  border: 1px solid var(--el-border-color-lighter);
  margin-bottom: 20px;
}

/* 新增：移除容器内最后一张卡的下边距，避免多余的空白 */
.person-card:last-child {
  margin-bottom: 0;
}

/* 调整卡片内的表单项，使其更紧凑 */
.person-card .el-form-item {
  margin-bottom: 18px;
}

.action-buttons {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  gap: 10px; /* 按钮之间的间距 */
}

.form-footer {
  margin-top: 20px;
}
</style>
